package org.javaymw.springboot.controller.activiti.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.javaymw.springboot.util.MessageUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/10/15 18:35
 * @Description: 模型管理
 */
@Controller
@RequestMapping("/admin/models")
public class ModelerController extends AbstractActivitiController {

    /**
     * 获取所有流程模型列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(org.springframework.ui.Model model) {
        List<Model> models = repositoryService.createModelQuery().list();
        model.addAttribute("models", models);
        return "admin/workflow/modelList";
    }

    /**
     * 创建一个空模型
     * @return
     */
    @GetMapping("/newModel")
    public String newModel() {
        try {
            //初始化一个空模型
            Model model = repositoryService.newModel();

            //设置一些默认信息
            String name = "new-process";
            String description = "";
            int revision = 1;
            String key = "process";

            ObjectNode modelNode = objectMapper.createObjectNode();
            modelNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelNode.put(ModelDataJsonConstants.MODEL_REVISION, revision);

            model.setName(name);
            model.setKey(key);
            model.setMetaInfo(modelNode.toString());

            repositoryService.saveModel(model);
            String id = model.getId();

            //完善ModelEditorSource
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            repositoryService.addModelEditorSource(id,editorNode.toString().getBytes("utf-8"));
            return "redirect:/editor?modelId="+id;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据Model部署流程
     * @param modelId
     * @return
     */
    @PostMapping("/{modelId}")
    @ResponseBody
    public Map<String, Object> deploy(@PathVariable("modelId") String modelId) {
        Map<String, Object> retMap = null;
        try {
            // 获取模型
            Model modelData = repositoryService.getModel(modelId);
            byte[] bytes = repositoryService.getModelEditorSource(modelData.getId());
            if (bytes == null) {
                retMap = MessageUtils.success("模型数据为空，请先设计流程并成功保存，再进行发布。");
                return retMap;
            }
            JsonNode modelNode = new ObjectMapper().readTree(bytes);
            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            if (model.getProcesses().size() == 0) {
                retMap = MessageUtils.success("数据模型不符要求，请至少设计一条主线流程。");
                return retMap;
            }
            byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
            // 发布流程
            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
            modelData.setDeploymentId(deployment.getId());

            /*repositoryService.saveModel(modelData);*/

            retMap = MessageUtils.success("部署成功");
        } catch (Exception e) {
            LOGGER.error("根据模型部署流程失败：modelId={}", modelId, e);
            retMap = MessageUtils.error("部署失败");
        }
        return retMap;
    }

    /**
     * 导出model的xml文件
     * @param modelId
     * @param response
     */
    @GetMapping(value = "/export/{modelId}")
    public void exportModel(@PathVariable("modelId") String modelId, HttpServletResponse response) {
        try {
            // 获取模型对象
            Model model = repositoryService.getModel(modelId);

            BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter();

            // 从模型对象中读取JSON数据
            JsonNode jsonNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(model.getId()));

            // 把JSON对象转换为BpmnModel
            BpmnModel bpmnModel = bpmnJsonConverter.convertToBpmnModel(jsonNode);

            BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();
            // 把BpmnModel对象转换成XML格式
            byte[] bytes = bpmnXMLConverter.convertToXML(bpmnModel);
            // 创建输入流输出文件内容到浏览器
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            IOUtils.copy(byteArrayInputStream, response.getOutputStream());

            String filename = bpmnModel.getMainProcess().getId() + ".bpm20.xml";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();

        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("导出model的xml文件失败：modelId={}", modelId, e);
        }
    }

    /**
     * 删除模型
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Map<String, Object> deleteModel(@PathVariable("id") String id){
        Map<String, Object> retMap = null;
        try {
            repositoryService.deleteModel(id);
            retMap = MessageUtils.success("删除成功");
            return retMap;
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

    /**
     * 同步用户 角色 用户角色到activiti表中
     * @return
     */
    @PostMapping(value = "/syncData")
    @ResponseBody
    public Map<String, Object> syncData() {
        Map<String, Object> retMap = null;
        try {
            // 异步同步数据
            syncDataService.syncData();
            retMap = MessageUtils.success("同步成功");
        } catch (Exception e) {
            retMap = MessageUtils.error("同步失败");
        }
        return retMap;
    }

}
